package com.shiningstars.activity;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.parse.ParseInstallation;
import com.shiningstars.R;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.tools.ExceptionHandler;

public class RegistrationActivity extends Activity implements Constants, Config, Messages {

	private ProgressDialog progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_registration);

			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			SplashPageActivity.showSplash = false;

			final EditText mobileNumberEditText = (EditText) this.findViewById(R.id.regEditText1);
			final Button okButton = (Button) this.findViewById(R.id.regButton1);
			final CheckBox acceptCheckBox = (CheckBox) this.findViewById(R.id.regCheckBox1);

			mobileNumberEditTextListener(mobileNumberEditText, acceptCheckBox, okButton);
			acceptCheckBoxListener(mobileNumberEditText, acceptCheckBox, okButton);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), RegistrationActivity.class.getName(), e);
		}
	}

	private boolean isButtonEnabled(EditText mobileNumberEditText, CheckBox acceptCheckBox) {
		if (acceptCheckBox.isChecked() && mobileNumberEditText.getText().length() == 10) {
			return true;
		}
		return false;
	}

	private void mobileNumberEditTextListener(final EditText mobileNumberEditText, final CheckBox acceptCheckBox,
			final Button okButton) {
		mobileNumberEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				okButton.setEnabled(isButtonEnabled(mobileNumberEditText, acceptCheckBox));
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				if (!mobileNumberEditText.getText().toString().equals(BLANK)) {
					try {
						Long.parseLong(mobileNumberEditText.getText().toString());
					} catch (NumberFormatException e) {
						mobileNumberEditText.setText(BLANK);
						Toast.makeText(getApplicationContext(), INVALID_MOBILE_NUMBER, Toast.LENGTH_LONG).show();
					}
				}
			}
		});
	}

	private void acceptCheckBoxListener(final EditText mobileNumberEditText, final CheckBox acceptCheckBox,
			final Button okButton) {
		acceptCheckBox.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				okButton.setEnabled(isButtonEnabled(mobileNumberEditText, acceptCheckBox));
			}
		});
	}

	public void showTermsConditions(final View view) {
		try {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.popup_terms_conditions, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			view.post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
				}
			});

			Button btnAccept = (Button) popupView.findViewById(R.id.accept);
			btnAccept.setOnClickListener(new Button.OnClickListener() {

				@Override
				public void onClick(View v) {
					popupWindow.dismiss();
				}
			});
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), RegistrationActivity.class.getName(), e);
		}
	}

	public void registerUser(final View view) {
		try {
			progress = new ProgressDialog(this);
			progress.setTitle(REGISTERING_USER);
			progress.setMessage(PLEASE_WAIT);
			progress.setCancelable(false);
			progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

			AlertDialog.Builder builder = new AlertDialog.Builder(RegistrationActivity.this);

			builder.setMessage(REGISTRATION_SMS_MSG);
			builder.setCancelable(false);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					progress.show();
					new Thread() {
						@Override
						public void run() {

							Looper.prepare();

							TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
							final String imeiNumber = manager.getDeviceId();
							final String mobileNumber = ((EditText) findViewById(R.id.regEditText1)).getText()
									.toString();

							final Map<String, String> dataMap = new HashMap<String, String>();

							dataMap.put(IMEI_NUMBER, imeiNumber);
							dataMap.put(MOBILE_NUMBER, mobileNumber);
							dataMap.put(VERSION, APP_VERSION);

							String message = REGISTRATION_ERROR;

							try {
								WebHelper webHelper = new WebHelper();
								JSONObject json = webHelper.registerUser(dataMap, getApplicationContext());

								if (null != json && json.getBoolean(SUCCESS)) {

									if (IS_PROD) {
										SmsManager smsManager = SmsManager.getDefault();
										smsManager.sendTextMessage(SAURABH_MOBILE, null, imeiNumber, null, null);
									}

									JSONObject profile = json.getJSONObject(PROFILE);
									String role = profile.getString(ROLE);
									String name = profile.getString(FIRST_NAME) + SPACE + profile.getString(LAST_NAME);

									ParseInstallation.getCurrentInstallation().put(NAME, name);
									ParseInstallation.getCurrentInstallation().put(MOBILE_NUMBER, mobileNumber);
									ParseInstallation.getCurrentInstallation().put(IMEI_NUMBER, imeiNumber);
									ParseInstallation.getCurrentInstallation().addAll(CHANNELS, Arrays.asList(role));
									ParseInstallation.getCurrentInstallation().saveInBackground();

									Utilities.setSharedPreference(getApplicationContext(), ROLE, role);
									Utilities.setSharedPreference(getApplicationContext(), STATUS, PENDING);
									Utilities.setSharedPreference(getApplicationContext(), NAME, name);
									Utilities.setSharedPreference(getApplicationContext(), MOBILE_NUMBER, mobileNumber);
									Utilities.setSharedPreference(getApplicationContext(), IMEI_NUMBER, imeiNumber);

									message = REGISTRATION_SUCCESS;
								} else {
									message = REGISTRATION_FAILED;
								}
							} catch (JSONException e) {
								Utilities.logError(getApplicationContext(), RegistrationActivity.class.getName(), e);
							} catch (IllegalStateException e) {
								Utilities.logError(getApplicationContext(), RegistrationActivity.class.getName(), e);
							} catch (IOException e) {

							}

							final boolean isSuccess = message.equals(REGISTRATION_SUCCESS) ? true : false;

							AlertDialog.Builder builder = new AlertDialog.Builder(RegistrationActivity.this);

							builder.setMessage(message);
							builder.setCancelable(false);
							builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									if (isSuccess) {
										finish();
									}
								}
							});

							progress.dismiss();

							AlertDialog alert = builder.create();
							alert.show();

							Looper.loop();
							Looper.myLooper().quit();
						}
					}.start();
				}
			});

			builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), RegistrationActivity.class.getName(), e);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		SplashPageActivity.showSplash = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (SplashPageActivity.showSplash) {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.activity_splash_page, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			findViewById(R.id.regTextView1).post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(findViewById(R.id.regTextView1), Gravity.CENTER, 0, 0);
				}
			});

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					popupWindow.dismiss();
				}
			}, SPLASH_TIME_OUT);

			SplashPageActivity.showSplash = false;
		}
	}
}